package com.shelpe.services.sinbad.utils;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

public class DateUtil {

	public static Date parseDate(String str, Date defaultValue) {
		if (StringUtils.isNotBlank(str)) {
			try {
				defaultValue = DateUtils.parseDate(str, "yyyy-MM-dd HH:mm:ss");
			} catch (ParseException e) {
			}
		}
		return defaultValue;
	}

	public static Date parseDate(String str) {
		return DateUtil.parseDate(str, null);
	}

	public static long convertBetweenDay(Date start, Date end) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(start);
		long createTime = cal.getTimeInMillis();
		cal.setTime(end);
		long pauseTime = cal.getTimeInMillis();
		return (pauseTime - createTime) / (1000 * 3600 * 24);
	}

	public static int compareBetweenDay(Date date1, Date date2) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date1);
		int start = cal.get(Calendar.DAY_OF_MONTH);
		cal.setTime(date2);
		int end = cal.get(Calendar.DAY_OF_MONTH);
		return start - end;
	}

	public static double formatDouble2(double d) {
//		NumberFormat nf = NumberFormat.getNumberInstance();
//		// 保留两位小数
//		nf.setMaximumFractionDigits(2);
//		// 如果不需要四舍五入，可以使用RoundingMode.DOWN
//		nf.setRoundingMode(RoundingMode.UP);此方法针对三位数的double类型
		return (double)Math.round(d*100)/100;
	}

	public static Date parseDate(long time) {
		return new Date(time);
	}

	public static Date parseDate2min(String str) {
		if (StringUtils.isNotBlank(str)) {
			try {
				return DateUtils.parseDate(str, "yyyy-MM-dd HH:mm");
			} catch (ParseException e) {

			}
		}
		return null;
	}

	public static Date parseDate2date(String str) {
		if (StringUtils.isNotBlank(str)) {
			try {
				return DateUtils.parseDate(str, "yyyy-MM-dd");
			} catch (ParseException e) {

			}
		}
		return null;
	}

	public static long checkTime(Date nowDate, Date dbDate) {
		Calendar cal1 = Calendar.getInstance();
		cal1.setTime(nowDate);
		cal1.set(Calendar.HOUR_OF_DAY, 0);
		cal1.set(Calendar.MINUTE, 0);
		cal1.set(Calendar.SECOND, 0);
		cal1.set(Calendar.MILLISECOND, 0);
		Calendar cal2 = Calendar.getInstance();
		cal2.setTime(dbDate);
		cal2.set(Calendar.HOUR_OF_DAY, 0);
		cal2.set(Calendar.MINUTE, 0);
		cal2.set(Calendar.SECOND, 0);
		cal2.set(Calendar.MILLISECOND, 0);
		
		return cal1.getTime().getTime() - cal2.getTime().getTime();
	}
}
